package com.zeny.coding.service.impl;


import com.zeny.coding.constants.CourseConstants;
import com.zeny.coding.dto.RoleUserDto;
import com.zeny.coding.entity.RoleUser;
import com.zeny.coding.entity.RoleUserExample;
import com.zeny.coding.mapper.RoleUserMapper;
import com.zeny.coding.service.RoleUserService;
import com.zeny.coding.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <h2>TODO</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
@Slf4j
@Service
public class RoleUserServiceImpl implements RoleUserService {

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Transactional
    @Override
    public void saveBatch(RoleUserDto roleUserDto) {
        //删除原来的分配
        RoleUserExample example = new RoleUserExample();
        String userId = roleUserDto.getUserId();
        example.createCriteria().andUserIdEqualTo(userId);
        this.roleUserMapper.deleteByExample(example);
        //新增
        List<String> roleIds = roleUserDto.getRoleIds();
        if (CollectionUtils.isEmpty(roleIds)) {
            log.info("用户分配的角色id为空, 删除后直接返回");
            return;
        }
        SnowFlake snowFlake = new SnowFlake(CourseConstants.dataCenterId, CourseConstants.machineId);
        for (String roleId : roleIds) {
            RoleUser roleUser = new RoleUser();
            roleUser.setId(String.valueOf(snowFlake.nextId()));
            roleUser.setRoleId(roleId);
            roleUser.setUserId(userId);
            this.roleUserMapper.insertSelective(roleUser);
        }
    }
}
